from django.db.models import Q
from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serializers.orders import OrderListSerializer, OrderDetailSerializer, OrderStatusSerializer
from orders.models import OrderInfo


class OrderViewSet(ReadOnlyModelViewSet):
    permission_classes = [IsAdminUser]

    #指定序列化器类
    serializer_class = OrderListSerializer

    @action(methods=['put'], detail=True)
    def status(self,request,pk):
        """修改订单状态
        1.校验订单是否有效
        2.获取订单status并校验，status必传，status是否合法
        3.修改并保存订单状态
        4.返回
        """
        # 1.校验订单是否有效
        order = self.get_object()
        # 2.获取订单status并校验，status必传，status是否合法
        serializer = OrderStatusSerializer(order,data = request.data)
        serializer.is_valid(raise_exception=True)
        # 3.修改并保存订单状态
        serializer.save()
        # 4.返回
        return Response(serializer.data)




    def get_serializer_class(self):
        """返回视图所使用的序列化器类"""
        if self.action =='list':
            return OrderListSerializer
        else:
            return OrderDetailSerializer

    def get_queryset(self):
        #获取关键字
        keyword = self.request.query_params.get('keyword')

        if not keyword:
            orders = OrderInfo.objects.all()
        else:
            orders = OrderInfo.objects.filter(Q(order_id=keyword) |
                                            Q(skus__sku__name__contains=keyword))

        return orders